/*
 * Copyright (C) 2012, EADS France
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */
package xowl.interpreter.frontends.functional;

/**
 *
 * @author Laurent WOUTERS
 */
public class QueriesLoader extends Loader {
    private xowl.lang.owl2.Ontology ontology;
    private xowl.interpreter.frontends.QueriesListener listener;

    public QueriesLoader(String input, xowl.interpreter.frontends.QueriesListener listener) {
        super(input);
        this.listener = listener;
    }

    @Override public xowl.lang.owl2.IRI getIRI(String fullIRI) { return listener.getIRI(fullIRI); }
    
    public xowl.lang.owl2.Ontology load(xowl.utils.logging.Logger logger, FElementNode node) throws FParserException {
        String iri = ((FIRINode)node.getChildren().get(0)).getIRI();
        ontology = listener.resolveOntology(listener.getIRI(iri));
        for (FNode child : node.getChildren()) {
            if (child.getType() != FNodeType.Element)
                continue;
            FElementNode elem = (FElementNode)child;
            try {
                if (xowl.interpreter.frontends.VocActions.qrySelectAll.equals(elem.getName())) {
                    // Treat SelectAll
                    xowl.lang.actions.Select select = load_SelectAll((FElementNode)child);
                    listener.onSelect(select);
                }
            } catch (java.lang.Exception ex) {
                logger.error(FunctionalLoader.name, "Functional Loader: Failed to load element at line " + elem.getLine(), ex);
            }
        }
        return ontology;
    }
    
    private xowl.lang.actions.Select load_SelectAll(FElementNode node) throws FParserException {
        xowl.interpreter.frontends.LexicalContext context = new xowl.interpreter.frontends.LexicalContext();
        xowl.lang.actions.SelectAll query = new xowl.lang.actions.SelectAll();
        query.setHasIRI(listener.getIRI(((FIRINode)node.getChildren().get(0)).getIRI()));
        for (int i=1; i!=node.getChildren().size(); i++) {
            FNode child = node.getChildren().get(i);
            if (child.getType() != FNodeType.Element)
                continue;
            xowl.lang.owl2.Axiom axiom = AxiomLoader.load(this, (FElementNode)child, context);
            if (axiom != null)
                query.addAxioms(axiom);
        }
        return query;
    }
}
